﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;

namespace ERP_RORZE_TOOL.Tool.Forms
{
	public partial class frm_BrokenAdd : DevExpress.XtraEditors.XtraForm
	{
		private ucBroken parent;
        private ucBorrow parentBorrow;
	    private bool firstLoadFromBorrow = true;
        public string ToolId;
        public string MachineId;
        public bool FromBorrow;

		private DataTable dt = new DataTable();
		//private DataTable dtToKind = new DataTable();

        public frm_BrokenAdd(ucBroken fBroken=null, ucBorrow fBorrow = null, bool isFromBorrow = false)
		{
            InitializeComponent();
            btAdd.Image = ERP_RORZE_TOOL.Properties.Resources.add;
            btCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
			parent = fBroken;
            parentBorrow = fBorrow;
            FromBorrow = isFromBorrow;
			this.CancelButton = this.btCancel;
		}
        
		private void XtraForm1_Load(object sender, EventArgs e)
		{
		    if (FromBorrow)
		    {
                dtpTDate.Value = DateTime.Today;
                BindDataMistake();
                BindDataMachine();
                BindDataStatus();
                BindDataPart();
                BindDataProcessStatus();
                BindDataRotate();
                BindDataFromBorrow();
                BindDataToKind();
                rdDelete.Checked = true;
                
		        firstLoadFromBorrow = false;
		    }
		    else
		    {
                dtpTDate.Value = DateTime.Today;
                BindDataTool();
                BindDataMistake();
                BindDataMachine();
                BindDataStatus();
                BindDataPart();
                BindDataProcessStatus();
                BindDataRotate();
                BindDataToKind();
                rdDelete.Checked = true;
		    }
			
		}

		private void btTAdd_Click_1(object sender, EventArgs e)
		{
			AddTool();
		}

		private void btTCancel_Click_1(object sender, EventArgs e)
		{
			this.Close();
		}

		private void rdDelete_CheckedChanged(object sender, EventArgs e)
		{
			lblSelecTool.Enabled = false;
			cmbToKind.SelectedItem = cmbToKind.Items[0];
			cmbToKind.Enabled = false;
		}

		private void rdChangekind_CheckedChanged(object sender, EventArgs e)
		{
			lblSelecTool.Enabled = true;
			cmbToKind.Enabled = true;
		}

        private void cmbMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMachine.SelectedItem != cmbMachine.Items[0] && !FromBorrow)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.SelectedValue + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.SelectedValue + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                if (number <= 0)
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else if (cmbMachine.SelectedItem != cmbMachine.Items[0] && FromBorrow && !firstLoadFromBorrow)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.SelectedValue + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.SelectedValue + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                if (number <= 0)
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }
		#region Private methods

		private bool GetDataTool(Broken o)
		{
			#region Check valid

			if(Utilities.IsNullOrEmpty(dtpTDate.Value.ToString()))
			{
				MessageBox.Show(ToolConstants.Message.Broken.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (Utilities.IsNullOrEmpty(cmbToolID.SelectedValue) || cmbToolID.SelectedItem == cmbToolID.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (Utilities.IsNullOrEmpty(cmbMachine.SelectedValue) || cmbMachine.SelectedItem == cmbMachine.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.MachineCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (Utilities.IsNullOrEmpty(cmbMistake.SelectedValue) || cmbMistake.SelectedItem == cmbMistake.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.MistakeCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (Utilities.IsNullOrEmpty(cmbStatus.SelectedValue) || cmbStatus.SelectedItem == cmbStatus.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.StatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			if(Utilities.IsNullOrEmpty(txtLossNo.Text.Trim()))
			{
				MessageBox.Show(ToolConstants.Message.Broken.LossNoCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}


            if (Utilities.IsNullOrEmpty(cmbPart.SelectedValue) || cmbPart.SelectedItem == cmbPart.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.PartCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			if(Utilities.IsNullOrEmpty(txtQuantity.Text.Trim()))
			{
				MessageBox.Show(ToolConstants.Message.Broken.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (int.Parse(txtQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQuantity.Focus();
                return false;

            }

            if (int.Parse(txtQuantity.Text) > 0)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.SelectedValue + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.SelectedValue + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);


                if (number < int.Parse(txtQuantity.Text))
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.WrongQuantity, cmbMachine.SelectedValue, number.ToString(), txtQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtQuantity.Focus();
                    return false;
                }

            }

            if (Utilities.IsNullOrEmpty(cmbProcessStatus.SelectedValue) || cmbProcessStatus.SelectedItem == cmbProcessStatus.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.ProcessStatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            if (Utilities.IsNullOrEmpty(cmbRotate.SelectedValue) || cmbRotate.SelectedItem == cmbRotate.Items[0])
			{
				MessageBox.Show(ToolConstants.Message.Broken.RotateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

            //if(Utilities.IsNullOrEmpty(txtStandardSpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.StandardSpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            //if(Utilities.IsNullOrEmpty(txtRealitySpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.RealitySpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

			if(rdChangekind.Checked)
			{

                if (Utilities.IsNullOrEmpty(cmbToKind.SelectedValue) || cmbToKind.SelectedItem == cmbToKind.Items[0])
				{
					MessageBox.Show(ToolConstants.Message.Broken.ToKindCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
			}
			#endregion

			o.Date = dtpTDate.Value;
			o.ToolID = cmbToolID.SelectedValue.ToString();
			o.MachineID = cmbMachine.SelectedValue.ToString();
			o.MistakeID = cmbMistake.SelectedValue.ToString();
            o.StatusName = cmbStatus.SelectedValue.ToString();
			o.LossNo = txtLossNo.Text;
            o.PartNo = cmbPart.SelectedValue.ToString();
			o.Quantity = int.Parse(txtQuantity.Text);
			o.ProcessStatusID = cmbProcessStatus.SelectedValue.ToString();
			o.RotateID = cmbRotate.SelectedValue.ToString();
			o.StandardSpeed = txtStandardSpeed.Text;
			o.RealitySpeed = txtRealitySpeed.Text;
			if(rdChangekind.Checked)
			{
				o.Process = ToolConstants.Configuration.ProcessStatus.TrueStr;
				o.ToKind = cmbToKind.SelectedValue.ToString();
			}
			else
			{
				o.Process = ToolConstants.Configuration.ProcessStatus.FalseStr;
				o.ToKind = "";

			}
			o.Note = memoTNote.Text;

			return true;
		}

		private void BindDataTool()
		{
			ToolHelper helper = new ToolHelper(new Tools());
			dt = helper.GetAllByToolType();
			DataRow row = dt.NewRow();


            row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
			row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
			dt.Rows.InsertAt(row, 0);

            cmbToolID.DataSource = dt;
            cmbToolID.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
            cmbToolID.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

			cmbToolID.SelectedItem = cmbToolID.Items[0];
		}

		private void BindDataMistake()
		{
			MistakeHelper helper = new MistakeHelper(new Mistake());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Mistake.FieldName.FullName] = "Select...";
			row[ToolConstants.Entities.Mistake.FieldName.MistakeID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbMistake.DataSource = dt;
            cmbMistake.DisplayMember = ToolConstants.Entities.Mistake.FieldName.FullName;
            cmbMistake.ValueMember = ToolConstants.Entities.Mistake.FieldName.MistakeID;

			cmbMistake.SelectedItem = cmbMistake.Items[0];
		}

		private void BindDataMachine()
		{
			MachineHelper helper = new MachineHelper(new Machine());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Machine.FieldName.FullName] = "Select...";
			row[ToolConstants.Entities.Machine.FieldName.MachineID] = null;
			dt.Rows.InsertAt(row, 0);

            cmbMachine.DataSource = dt;
            cmbMachine.DisplayMember = ToolConstants.Entities.Machine.FieldName.FullName;
            cmbMachine.ValueMember = ToolConstants.Entities.Machine.FieldName.MachineID;
			cmbMachine.SelectedItem = cmbMachine.Items[0];
		}

		private void BindDataStatus()
		{
			ToolStatusHelper helper = new ToolStatusHelper(new ToolStatus());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

			
            row[ToolConstants.Entities.ToolStatus.FieldName.StatusName] = "Select...";
			dt.Rows.InsertAt(row, 0);

            cmbStatus.DataSource = dt;
            cmbStatus.DisplayMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;
            cmbStatus.ValueMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;

			cmbStatus.SelectedItem = cmbStatus.Items[0];
		}

		private void BindDataPart()
		{
			PartHelper helper = new PartHelper(new Part());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Part.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Part.FieldName.PartNo] = DBNull.Value;
			dt.Rows.InsertAt(row, 0);

            cmbPart.DataSource = dt;
            cmbPart.DisplayMember = ToolConstants.Entities.Part.FieldName.FullName;
            cmbPart.ValueMember = ToolConstants.Entities.Part.FieldName.PartNo;
			cmbPart.SelectedItem = cmbPart.Items[0];
		}

		private void BindDataProcessStatus()
		{
			ProcessStatusHelper helper = new ProcessStatusHelper(new ProcessStatus());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

            row[ToolConstants.Entities.ProcessStatus.FieldName.FullName] = "Select...";
			row[ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID] = null;
			dt.Rows.InsertAt(row, 0);

            cmbProcessStatus.DataSource = dt;
            cmbProcessStatus.DisplayMember = ToolConstants.Entities.ProcessStatus.FieldName.FullName;
            cmbProcessStatus.ValueMember = ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID;
			cmbProcessStatus.SelectedItem = cmbProcessStatus.Items[0];
		}

		private void BindDataRotate()
		{
			RotateHelper helper = new RotateHelper(new Rotate());
			DataTable dt = helper.GetAll();
			DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Rotate.FieldName.FullName] = "Select...";
			row[ToolConstants.Entities.Rotate.FieldName.RotateID] = null;
			dt.Rows.InsertAt(row, 0);

            cmbRotate.DataSource = dt;
            cmbRotate.DisplayMember = ToolConstants.Entities.Rotate.FieldName.FullName;
            cmbRotate.ValueMember = ToolConstants.Entities.Rotate.FieldName.RotateID;
			cmbRotate.SelectedItem = cmbRotate.Items[0];
		}

		private void BindDataToKind()
		{
			DataRow row;

			if(dt.Rows.Count == 0)
			{
				ToolHelper helper = new ToolHelper(new Tools());
                dt = helper.GetAllByToolType();
                row = dt.NewRow();
				
				row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
				row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
                dt.Rows.InsertAt(row, 0);

                cmbToKind.DataSource = dt;
                cmbToKind.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
                cmbToKind.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

				cmbToKind.SelectedItem = cmbToKind.Items[0];
			}
			else
			{
                row = dt.NewRow();
                row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
                row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
                //dt.Rows.InsertAt(row, 0);

                cmbToKind.DataSource = dt;
				cmbToKind.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
				cmbToKind.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;
				
				cmbToKind.SelectedItem = cmbToKind.Items[0];
			}

			
		}

		private void AddTool()
		{
			BrokenHelper helper = new BrokenHelper(new Broken());
			if(GetDataTool(helper.ValueObject))
			{

				if(helper.Insert() > 0)
				{
				    if (Utilities.MessageConfirmationYesNo(ToolConstants.Message.AddSuccessAndQuestion))
				    {

				        dtpTDate.Value = DateTime.Now;
				        cmbToolID.SelectedItem = cmbToolID.Items[0];
				        cmbMachine.SelectedItem = cmbMachine.Items[0];
				        cmbMistake.SelectedItem = cmbMistake.Items[0];
				        cmbStatus.SelectedItem = cmbStatus.Items[0];
				        cmbPart.SelectedItem = cmbPart.Items[0];
				        cmbProcessStatus.SelectedItem = cmbProcessStatus.Items[0];
				        cmbRotate.SelectedItem = cmbRotate.Items[0];
				        txtLossNo.Text = "";
				        memoTNote.Text = "";
				        txtQuantity.Text = "";
				        txtStandardSpeed.Text = "";
				        txtRealitySpeed.Text = "";
				        rdDelete.Checked = true;
				        dtpTDate.Focus();
				    }
				    else
				    {
				        this.Close();
				    }
				}
				else
				{
                    Utilities.MessageErrorOk(ToolConstants.Message.AddFailed);
				}
                if (parent != null)
			    {
                    parent._action = 0;
                    parent.BindDatatoGrid();
			    }
                if (FromBorrow)
                {
                    parentBorrow.BindDatatoBroken();
                }

			}
		}

        private void BindDataFromBorrow()
        {
            BindDataTool();

            cmbToolID.SelectedValue = ToolId;
            cmbMachine.SelectedValue = MachineId;

            if (cmbToolID.SelectedItem == null)
            {
                cmbToolID.SelectedItem = cmbToolID.Items[0];
            }

            if (cmbMachine.SelectedItem == null)
            {
                cmbMachine.SelectedItem = cmbMachine.Items[0];
            }
            //int instockAtpresent = CheckInputTool();
            //lblStatus.Visible = true;
            //lblStatus.Text = string.Format(ToolConstants.Message.Borrow.ToolInStock, cmbToolID.SelectedValue, instockAtpresent.ToString());


        }
		#endregion

        

	}
}